package com.example.CarManagement.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.CarManagement.Utils.sysUtils;
import com.example.CarManagement.common.Result;
import com.example.CarManagement.enumPojo.DriverStatus;
import com.example.CarManagement.sys.entity.CarInfo;
import com.example.CarManagement.sys.entity.Drivers;
import com.example.CarManagement.sys.entity.UserRole;
import com.example.CarManagement.sys.mapper.CarInfoMapper;
import com.example.CarManagement.sys.mapper.DriversMapper;
import com.example.CarManagement.sys.mapper.UserRoleMapper;
import com.example.CarManagement.sys.service.IDriversService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 司机信息表，存储所有司机的专业信息和当前状态 服务实现类
 * </p>
 *
 * @author 徐佳彪
 * @since 2025-07-17
 */
@Service
public class DriversServiceImpl extends ServiceImpl<DriversMapper, Drivers> implements IDriversService {
    @Resource
    private UserRoleMapper userRoleMapper;


    @Resource
    private CarInfoMapper carInfoMapper;


    @Value("${sysRoleId.driver}")
    private String driverRoleId;

    public Result<?> getDrivers(Integer pageNo, Integer pageSize, String driverId) {
        LambdaQueryWrapper<Drivers> driversLambdaQueryWrapper = new LambdaQueryWrapper<>();

        if (driverId != null) {
            driversLambdaQueryWrapper.like(Drivers::getDriverId, driverId);
        }

        driversLambdaQueryWrapper.orderByDesc(Drivers::getCreatedAt);

        Page<Drivers> driversPage = this.baseMapper.selectPage(new Page<>(pageNo, pageSize), driversLambdaQueryWrapper);

        // 角色总数
        Integer total = (int) driversPage.getTotal();


        List<Drivers> drivers = driversPage.getRecords();

        Map<String, Object> data = new HashMap<>();
        data.put("rows", drivers);
        data.put("total", total);

        return Result.success(data);
    }

    @Override
    public Result<?> addDrivers(Drivers drivers) {


        // 判断当前用户是否为司机
        String userId = drivers.getUserId();

        LambdaQueryWrapper<Drivers> driversLambdaQueryWrapper = new LambdaQueryWrapper<>();
        driversLambdaQueryWrapper.eq(Drivers::getUserId, userId);

        Drivers oldDrivers = this.baseMapper.selectOne(driversLambdaQueryWrapper);

        if (oldDrivers != null) {
            return Result.fail("当前用户已经是司机");
        }

        // 生成工号
        String driverId = sysUtils.createId("DRIVER");
        drivers.setDriverId(driverId);

        // 设置用户权限为司机
        drivers.setDriverRoleId(driverRoleId);
        // 查询角色权限表，如果存在权限就修改，不存在权限就添加
        LambdaQueryWrapper<UserRole> userRoleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userRoleLambdaQueryWrapper.eq(UserRole::getUserId, userId);
        UserRole oldUserRole = userRoleMapper.selectOne(userRoleLambdaQueryWrapper);
        if (oldUserRole != null) {
            oldUserRole.setRoleId(driverRoleId);
            userRoleMapper.updateById(oldUserRole);
        } else {
            UserRole userRole = new UserRole();
            userRole.setId(UUID.randomUUID().toString());
            userRole.setUserId(userId);
            userRole.setRoleId(driverRoleId);
            userRoleMapper.insert(userRole);
        }


        drivers.setCreatedAt(LocalDateTime.now());
        drivers.setUpdatedAt(LocalDateTime.now());

        // 添加司机信息
        this.baseMapper.insert(drivers);
        return Result.success("添加成功");

    }

    @Override
    public Result<?> updateDrivers(Drivers drivers) {
        drivers.setUpdatedAt(LocalDateTime.now());
        LambdaQueryWrapper<Drivers> driversLambdaQueryWrapper = new LambdaQueryWrapper<>();
        driversLambdaQueryWrapper.eq(Drivers::getDriverId, drivers.getDriverId());
        this.baseMapper.update(drivers, driversLambdaQueryWrapper);

        return Result.success("修改成功");
    }


    @Override
    public Result<?> getDriversById(String driverId) {
        LambdaQueryWrapper<Drivers> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Drivers::getDriverId, driverId);
        Drivers drivers = this.baseMapper.selectOne(lambdaQueryWrapper);

        return Result.success(drivers);
    }

    @Override
    public Result<?> deleteDrivers(String driverId) {
        // 判断当前司机是否为出勤
        LambdaQueryWrapper<Drivers> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Drivers::getDriverId, driverId);
        Drivers drivers = this.baseMapper.selectOne(lambdaQueryWrapper);

        if (drivers.getStatus() == DriverStatus.on_duty) {
            return Result.fail("无法删除出勤的司机");
        }

        this.baseMapper.delete(lambdaQueryWrapper);

        return Result.fail("删除成功");
    }

    @Override
    public Result<?> assignCar(String driverId, String carId) {
        // 查询改汽车是否可用
        CarInfo carInfo = carInfoMapper.selectById(carId);
        if (carInfo.getStatus() != 0) {
            return Result.fail("该汽车不可用");
        }

        // 查询改汽车是否已被分配
        LambdaQueryWrapper<Drivers> driversLambdaQueryWrapper = new LambdaQueryWrapper<>();
        driversLambdaQueryWrapper.eq(Drivers::getCurrentVehicleId, carId);
        Drivers oldDrivers = this.baseMapper.selectOne(driversLambdaQueryWrapper);
        if (oldDrivers != null) {
            return Result.fail("该汽车已被分配");
        }


        // 分配汽车
        LambdaQueryWrapper<Drivers> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Drivers::getDriverId, driverId);
        Drivers od = this.baseMapper.selectOne(lambdaQueryWrapper);
        od.setCurrentVehicleId(carId);
        LambdaQueryWrapper<Drivers> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Drivers::getDriverId, driverId);
        od.setUpdatedAt(LocalDateTime.now());
        this.baseMapper.update(od, queryWrapper);

        // 设置车辆
        LambdaQueryWrapper<CarInfo> carInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        carInfoLambdaQueryWrapper.eq(CarInfo::getId, carId);
        CarInfo oldCar = carInfoMapper.selectOne(carInfoLambdaQueryWrapper);
        oldCar.setAssignedDriverId(od.getDriverId());
        carInfoMapper.update(oldCar, carInfoLambdaQueryWrapper);

        // 修改原来分配的车辆
        LambdaQueryWrapper<CarInfo> carInfoLambdaQueryWrapper2 = new LambdaQueryWrapper<>();
        carInfoLambdaQueryWrapper2.eq(CarInfo::getAssignedDriverId, driverId);
        CarInfo oldCar2 = carInfoMapper.selectOne(carInfoLambdaQueryWrapper2);
        if (oldCar2 != null) {
            oldCar2.setAssignedDriverId(null);
            carInfoMapper.update(oldCar2, carInfoLambdaQueryWrapper2);
        }

        return Result.success("分配成功");


    }
}
